package Socket03;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    private Socket socket ;
    private String name;
    /**
     * 构造器
     */
    public Client(){
        try {
            socket = new Socket("localhost",100);
            System.out.println("一个客户端已建立");
            name = socket.getInetAddress().getHostName();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端输出内容
     */
    public void start(){
        try {
            Thread t = new Thread(new ClientHandler());
            t.setDaemon(true);
            t.start();

            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream())),true);
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入：");
            String s;
            while (true){
                s = scan.next();
                if("exit".equalsIgnoreCase(s)){
                    break;
                }else {
                    pw.println(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class ClientHandler implements Runnable{

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));
                String s;
                while ((s = br.readLine()) != null){
                    System.out.println(name+"说："+s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 主方法
     * @param args
     */
    public static void main(String[] args) {
     Client client = new Client();
     client.start();
    }
}
